<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单位名称" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="组织编码" prop="unitCode">
        <el-input
          v-model="queryParams.unitCode"
          placeholder="请输入组织机构编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:unit:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:unit:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:unit:remove']"
          v-hasRole="['admin']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:unit:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange"
              :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="单位名称" align="center" prop="unitName"/>
      <el-table-column label="社会组织编码" align="center" prop="unitCode"/>
      <el-table-column label="企业类型" align="center" prop="unitType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit_type" :value="scope.row.unitType"/>
        </template>
      </el-table-column>
      <!--      <el-table-column label="主管单位" align="center" prop="superviseOrgId">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>-->
      <!--            {{getDictAllList(getSupervisorlnitList,'orgName',scope.row.superviseOrgId)}}-->
      <!--          </span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="联网单位状态" align="center" prop="onlineStatus">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.online_status" :value="scope.row.onlineStatus"/>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="维保开始日期" align="center" prop="maintenanceStartDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.maintenanceStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维保结束日期" align="center" prop="maintenanceEndDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.maintenanceEndDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推送状态" align="center" prop="pushStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.push_status" :value="scope.row.pushStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="创建用户" align="center" prop="createBy"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.pushStatus ==='2'"
                     size="mini"
                     type="text"
                     icon="el-icon-bottom"
                     @click="handleCancel(scope.row)"
                     v-hasPermi="['system:unit:edit']"
                     v-hasRole="['admin']"
          >取消推送
          </el-button>
          <el-button v-if="scope.row.pushStatus!=='2'"
                     size="mini"
                     type="text"
                     icon="el-icon-top"
                     @click="handleSort(scope.row)"
                     v-hasPermi="['system:unit:edit']"
          >推送
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:unit:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:unit:remove']"
            style="color: #ff0000;border: none"
            v-hasRole="['admin']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" inline>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="form.unitName" placeholder="请输入单位名称"/>
        </el-form-item>
        <el-form-item label="企业类型" prop="unitType">
          <el-select filterable v-model="form.unitType" placeholder="请选择企业类型" style="width: 200px">
            <el-option
              v-for="item in dict.type.unit_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联网状态" prop="onlineStatus">
          <el-select filterable v-model="form.onlineStatus" placeholder="请选择联网状态" style="width: 200px">
            <el-option
              v-for="item in dict.type.online_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="户籍化编码" prop="orgCode">
          <el-input v-model="form.orgCode" placeholder="请输入户籍化编码"/>
        </el-form-item>
        <el-form-item label="组织机构编码" prop="unitCode">
          <el-input v-model="form.unitCode" placeholder="请输入组织机构编码"/>
        </el-form-item>
        <el-form-item label="联网单位类型" prop="unitTypeId">
          <el-select filterable v-model="form.unitTypeId" placeholder="请选择联网单位类型" style="width: 200px">
            <el-option
              v-for="item in updateUnitList"
              :key="item.id"
              :label="item.unitTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属维保单位" prop="customMaintenanceUnitId">
          <el-select filterable v-model="form.customMaintenanceUnitId" placeholder="请选择所属维保单位"
                     style="width: 200px">
            <el-option
              v-for="item in customMaintenanceUnitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联网单位经济类型" prop="economicTypeId">
          <el-select filterable v-model="form.economicTypeId" placeholder="请选择经济类型" style="width: 200px">
            <el-option
              v-for="item in economicTypeList"
              :key="item.id"
              :label="item.economicTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="provinceId">
          <el-select filterable v-model="form.provinceId" placeholder="请选择省"
                     @change="getCityList(form.provinceId)" style="width: 200px">
            <el-option
              v-for="item in regionAllList"
              :key="item.id"
              :label="item.regionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="cityId">
          <el-select filterable v-model="form.cityId" placeholder="请选择城市"
                     @change="getDistrictList(form.cityId)" style="width: 200px">
            <el-option
              v-for="item in cityAllList"
              :key="item.id"
              :label="item.regionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区县" prop="districtId">
          <el-select filterable v-model="form.districtId" placeholder="请选择区县"
                     @change="getRegionList(form.districtId)" style="width: 200px">
            <el-option
              v-for="item in childrenAllList"
              :key="item.id"
              :label="item.regionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联网单位区域" prop="regionId">
          <el-select filterable v-model="form.regionId" placeholder="请选择联网单位区域" style="width: 200px">
            <el-option
              v-for="item in childrenAllList"
              :key="item.id"
              :label="item.regionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主管单位" prop="superviseOrgId">
          <el-select filterable v-model="form.superviseOrgId" placeholder="请选择主管单位" style="width: 200px">
            <el-option
              v-for="item in getSupervisorlnitList"
              :key="item.id"
              :label="item.orgName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入单位地址"/>
        </el-form-item>
        <el-form-item label="监管级别" prop="superviseLevelId">
          <el-select filterable v-model="form.superviseLevelId" placeholder="请选择监管级别" style="width: 200px">
            <el-option
              v-for="item in superviseLevelList"
              :key="item.id"
              :label="item.superviseLevelName"
              :value="item.id"
            />
          </el-select>
          <!--          <el-input v-model="form.superviseLevelId" placeholder="请输入监管级别id，通过单位基础数据接口获取"/>-->
        </el-form-item>
        <el-form-item label="单位联系电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入单位联系电话"/>
        </el-form-item>

        <el-form-item label="维保开始日期" prop="maintenanceStartDate">
          <el-date-picker clearable style="width: 200px"
                          v-model="form.maintenanceStartDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择维保开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维保结束日期" prop="maintenanceEndDate">
          <el-date-picker clearable style="width: 200px"
                          v-model="form.maintenanceEndDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择维保结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="国民经济行业分类" prop="industryId">
          <el-select filterable v-model="form.industryId" placeholder="请选择国民经济行业分类" style="width: 200px">
            <el-option
              v-for="item in industryAllList"
              :key="item.id"
              :label="item.industryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位所属行业" prop="industryBelongId">
          <el-select filterable v-model="form.industryBelongId" placeholder="请选择单位所属行业" style="width: 200px">
            <el-option
              v-for="item in belongAllList"
              :key="item.id"
              :label="item.industryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="单位标签" prop="unitTagIds">
          <el-select filterable v-model="form.unitTagIds" placeholder="请选择单位所属行业" style="width: 200px">
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.unitTagName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消责人" prop="responsibleManName">
          <el-input v-model="form.responsibleManName" placeholder="请输入消防安全责任人姓名"/>
        </el-form-item>
        <el-form-item label="消责人身份号码" prop="responsibleManId">
          <el-input v-model="form.responsibleManId" placeholder="请输入消防安全责任人公民身份号码"/>
        </el-form-item>
        <el-form-item label="消责人电话" prop="responsibleManTel">
          <el-input v-model="form.responsibleManTel" placeholder="请输入消防安全责任人电话"/>
        </el-form-item>
        <el-form-item label="消管人" prop="fireManagerName">
          <el-input v-model="form.fireManagerName" placeholder="请输入消防安全管理人姓名"/>
        </el-form-item>
        <el-form-item label="消管人证件号码" prop="fireManagerId">
          <el-input v-model="form.fireManagerId" placeholder="请输入消防安全管理人证件号码"/>
        </el-form-item>
        <el-form-item label="消管人电话" prop="fireManagerTel">
          <el-input v-model="form.fireManagerTel" placeholder="请输入消防安全关联人电话"/>
        </el-form-item>
        <el-form-item label="助理人姓名" prop="assistFireManagerName">
          <el-input v-model="form.assistFireManagerName" placeholder="请输入消防安全管理人助理人姓名"/>
        </el-form-item>
        <el-form-item label="助理人证件号码" prop="assistFireManagerId">
          <el-input v-model="form.assistFireManagerId" placeholder="请输入消防安全管理人助理人证件号码"/>
        </el-form-item>
        <el-form-item label="助理人电话" prop="assistFireManagerTel">
          <el-input v-model="form.assistFireManagerTel" placeholder="请输入消防安全管理人助理人电话"/>
        </el-form-item>
        <el-form-item label="法人代表姓名" prop="legalPersonName">
          <el-input v-model="form.legalPersonName" placeholder="请输入法人代表姓名"/>
        </el-form-item>
        <el-form-item label="法人代表证件号码" prop="legalPersonId">
          <el-input v-model="form.legalPersonId" placeholder="请输入法人代表证件号码"/>
        </el-form-item>
        <el-form-item label="法人代表电话" prop="legalPersonTel">
          <el-input v-model="form.legalPersonTel" placeholder="请输入法人代表电话"/>
        </el-form-item>
        <el-form-item label="职工总人数" prop="staffCount">
          <el-input v-model="form.staffCount" placeholder="请输入职工总人数"/>
        </el-form-item>
        <el-form-item label="管辖单位名称" prop="adminUnitName">
          <el-input v-model="form.adminUnitName" placeholder="请输入管辖单位名称"/>
        </el-form-item>
        <el-form-item label="固定资产" prop="fixedAssets">
          <el-input v-model="form.fixedAssets" placeholder="请输入固定资产，单位:万元"/>
        </el-form-item>
        <el-form-item label="占地面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入占地面积，单位：平方米"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积，单位：平方米"/>
        </el-form-item>
        <el-form-item label="联网日期" prop="onlineDate">
          <el-date-picker clearable style="width: 200px"
                          v-model="form.onlineDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择联网日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地图经度" prop="gpsLng">
          <el-input v-model="form.gpsLng" placeholder="请输入地图经度"/>
        </el-form-item>
        <el-form-item label="地图纬度" prop="gpsLat">
          <el-input v-model="form.gpsLat" placeholder="请输入地图纬度"/>
        </el-form-item>
        <!--        <el-form-item label="额外单位信息" prop="extraData">-->
        <!--          <el-input v-model="form.extraData" placeholder="请输入额外单位信息，自定义信息，长度限制256字符"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="成立时间" prop="establishedTime">
          <el-date-picker clearable style="width: 200px"
                          v-model="form.establishedTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择成立时间">
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="单位传真" prop="unitFix">-->
        <!--          <el-input v-model="form.unitFix" placeholder="请输入单位传真"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="邮政编码" prop="postcode">-->
        <!--          <el-input v-model="form.postcode" placeholder="请输入邮政编码"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="消防机构责任干部" prop="fireResponsibleLeader">-->
        <!--          <el-input v-model="form.fireResponsibleLeader" placeholder="请输入消防机构责任干部"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="营业时最大人数" prop="maxBusinessMans">-->
        <!--          <el-input v-model="form.maxBusinessMans" placeholder="请输入营业时最大人数"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="上级单位名称" prop="superiorUnitName">-->
        <!--          <el-input v-model="form.superiorUnitName" placeholder="请输入上级单位名称"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="单位消控室视频url" prop="controlCenterVideoUrl">
          <el-input v-model="form.controlCenterVideoUrl" type="textarea" :rows="6" placeholder="请输入单位消控室视频url"
                    style="width: 200px;"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="6" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="营业执照图片" prop="businessLicense">
          <el-upload style="width: 100%"
                     :action="upload.url"
                     :headers="upload.headers"
                     :file-list="upload.fileList"
                     :on-progress="handleFileUploadProgress"
                     :on-success="handleFileSuccess"
                     :on-error="handleFileError"
                     :before-upload="beforeFileUpload"
                     list-type="picture-card"
                     :limit="1"
                     :on-exceed="handleExceed"
                     :on-preview="handlePictureCardPreview"
          >
            <i class="el-icon-upload"></i>
<!--            <div slot="file" slot-scope="{file}">-->
<!--              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">-->
<!--              <span class="el-upload-list__item-actions">-->
<!--      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">-->
<!--        <i class="el-icon-zoom-in"></i>-->
<!--      </span>-->
<!--      <span class="el-upload-list__item-download" @click="handleDownload(file)">-->
<!--        <i class="el-icon-download"></i>-->
<!--      </span>-->
<!--    </span>-->
<!--            </div>-->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import {
  listUnit,
  getUnit,
  delUnit,
  addUnit,
  updateUnit,
  allList,
  regionAllList,
  unitAllList,
  economicAllList,
  belongAllList,
  industryAllList,
  childrenCityList,
  childrenDistrictList,
  tagAllList,
  superviseLevel,
  getSupervisorlnit, getSupervisorUnit, unitPush, deleteUnit
} from "@/api/system/unit"
import {parseTime} from "../../../utils/ruoyi";
import {getToken} from "@/utils/auth";
import {listUser} from "@/api/system/user";
// import dict from "@/utils/dict";

export default {
  name: "Unit",
  dicts: ['unit_type', 'online_status', 'push_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单位信息表格数据
      unitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitType: null,
        unitId: null,
        unitName: null,
        orgCode: null,
        unitTypeId: null,
        regionId: null,
        address: null,
        superviseOrgId: null,
        superviseLevelId: null,
        onlineStatus: null,
        unitCode: null,
        tel: null,
        customMaintenanceUnitId: null,
        controlCenterTel: null,
        maintenanceStartDate: null,
        maintenanceEndDate: null,
        industryId: null,
        unitTagIds: null,
        businessLicense: null,
        provinceId: null,
        cityId: null,
        districtId: null,
        responsibleManName: null,
        responsibleManId: null,
        responsibleManTel: null,
        fireManagerName: null,
        fireManagerId: null,
        fireManagerTel: null,
        assistFireManagerName: null,
        assistFireManagerId: null,
        assistFireManagerTel: null,
        legalPersonName: null,
        legalPersonId: null,
        legalPersonTel: null,
        staffCount: null,
        adminUnitName: null,
        economicTypeId: null,
        fixedAssets: null,
        area: null,
        buildingArea: null,
        onlineDate: null,
        gpsLng: null,
        gpsLat: null,
        industryBelongId: null,
        gpsType: null,
        extraData: null,
        establishedTime: null,
        unitFix: null,
        postcode: null,
        fireResponsibleLeader: null,
        maxBusinessMans: null,
        controlCenterVideoUrl: null,
        superiorUnitName: null,
        pushStatus: null,
        createUserId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        unitType: [
          {required: true, message: "企业类型不能为空", trigger: "change"}
        ],
        unitId: [
          {required: true, message: "物联单位id不能为空", trigger: "blur"}
        ],
        unitName: [
          {required: true, message: "单位名称不能为空", trigger: "blur"}
        ],
        orgCode: [
          {required: true, message: "户籍化编码不能为空", trigger: "blur"}
        ],
        unitTypeId: [
          {required: true, message: "联网单位类型不能为空", trigger: "blur"}
        ],
        regionId: [
          {required: true, message: "联网单位所属区域不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "单位地址不能为空", trigger: "blur"}
        ],
        superviseOrgId: [
          {required: true, message: "主管单位不能为空", trigger: "blur"}
        ],
        superviseLevelId: [
          {required: true, message: "监管级别不能为空", trigger: "blur"}
        ],
        onlineStatus: [
          {required: true, message: "联网单位在线状态不能为空", trigger: "change"}
        ],
        unitCode: [
          {required: true, message: "组织机构编码不能为空", trigger: "blur"}
        ],
        customMaintenanceUnitId: [
          {required: true, message: "所属维保单位不能为空", trigger: "blur"}
        ],
        maintenanceStartDate: [
          {required: true, message: "维保开始日期不能为空", trigger: "blur"}
        ],
        maintenanceEndDate: [
          {required: true, message: "维保结束日期不能为空", trigger: "blur"}
        ],
        businessLicense: [
          {required: true, message: "营业执照图片不能为空", trigger: "blur"}
        ],
        economicTypeId: [
          {required: true, message: "联网单位经济类型不能为空", trigger: "blur"}
        ],
        provinceId: [
          {required: true, message: "省不能为空", trigger: "blur"}
        ],
        cityId: [
          {required: true, message: "城市不能为空", trigger: "blur"}
        ],
        districtId: [
          {required: true, message: "区县不能为空", trigger: "blur"}
        ],
      },
      updateUnitList: [],
      regionAllList: [],
      customMaintenanceUnitList: [],
      economicTypeList: [],
      belongAllList: [],
      industryAllList: [],
      superviseLevelList: [],
      tagList: [],
      cityAllList: [],
      childrenAllList: [],
      getSupervisorlnitList: [],
      unitLoading: false,

      // 图片上传参数
      upload: {
        // 是否显示弹出层（用户上传）
        open: false,
        // 弹出层标题（用户上传）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
        // 上传允许的文件类型
        fileTypes: [".jpg", ".jpeg", ".png", ".gif"],
        // 文件大小限制(MB)
        fileSize: 10
      },
      dialogImageUrl: '',
      dialogVisible: false,
      userList: [],
    }
  },
  created() {
    this.dictList()
    this.getList()
  },
  methods: {
    // dict,
    parseTime,
    /** 查询单位信息列表 */
    getList() {
      this.loading = true
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        unitType: null,
        unitId: null,
        unitName: null,
        orgCode: null,
        unitTypeId: null,
        regionId: null,
        address: null,
        superviseOrgId: null,
        superviseLevelId: null,
        onlineStatus: null,
        unitCode: null,
        tel: null,
        customMaintenanceUnitId: null,
        controlCenterTel: null,
        maintenanceStartDate: null,
        maintenanceEndDate: null,
        industryId: null,
        unitTagIds: null,
        businessLicense: null,
        provinceId: null,
        cityId: null,
        districtId: null,
        responsibleManName: null,
        responsibleManId: null,
        responsibleManTel: null,
        fireManagerName: null,
        fireManagerId: null,
        fireManagerTel: null,
        assistFireManagerName: null,
        assistFireManagerId: null,
        assistFireManagerTel: null,
        legalPersonName: null,
        legalPersonId: null,
        legalPersonTel: null,
        staffCount: null,
        adminUnitName: null,
        economicTypeId: null,
        fixedAssets: null,
        area: null,
        buildingArea: null,
        onlineDate: null,
        gpsLng: null,
        gpsLat: null,
        industryBelongId: null,
        gpsType: null,
        extraData: null,
        establishedTime: null,
        unitFix: null,
        postcode: null,
        fireResponsibleLeader: null,
        maxBusinessMans: null,
        controlCenterVideoUrl: null,
        superiorUnitName: null,
        pushStatus: null,
        createUserId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null
      }
      this.resetForm("form")
      // this.upload.fileList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 是否推送表格颜色
    tableRowClassName({row}) {
      if (row.pushStatus === '1') {
        return 'warning-row';
      } else if (row.pushStatus === '2') {
        return 'success-row';
      }
      return '';
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加单位信息"
      this.upload.fileList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUnit(id).then(response => {
        this.form = response.data
        if (this.form.businessLicense) {
          this.upload.fileList = [{
            name: '已上传图片',
            url: this.form.businessLicense
          }];
        }
        this.form.onlineStatus = JSON.stringify(response.data.onlineStatus)
        this.getCityList(this.form.provinceId)
        this.getDistrictList(this.form.cityId)
        this.getRegionList(this.form.districtId)
        this.open = true
        this.title = "修改单位信息"
      })

    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除单位名称为"' + row.unitName + '"的数据项？').then(function () {
        return delUnit(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/unit/export', {
        ...this.queryParams
      }, `unit_${new Date().getTime()}.xlsx`)
    },

    /** 推送按钮操作 */
    handleSort(row) {
      this.loading = true
      const id = row.id
      unitPush(id).then(response => {
        this.$modal.msgSuccess("推送成功！")
        this.getList()
        this.loading = false
      })
    },
    /** 取消推送按钮操作 */
    handleCancel(row) {
      const unitId = row.id
      deleteUnit(unitId).then(response => {
        this.$modal.msgSuccess("取消推送！")
        this.getList()
      })
    },
    dictList() {
      this.getUpdateUnit()
      this.getRegionAllList()
      this.getCustomMaintenanceUnit()
      this.getEconomicTypeList()
      this.getBelongAllList()
      this.getIndustryAllList()
      this.getSuperviseLevel()
      this.getTagAllList()
      // this.getUserList()
    },
    /** 用户 */
    getUserList() {
      listUser({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.userList = response.data
      })
    },
    /** 单位标签 */
    getTagAllList() {
      tagAllList().then(response => {
        this.tagList = response.data
      })
    },
    /** 监管等级 */
    getSuperviseLevel() {
      superviseLevel().then(response => {
        this.superviseLevelList = response.data
      })
    },
    /** 国民经济 */
    getIndustryAllList() {
      industryAllList().then(response => {
        this.industryAllList = response.data
      })
    },
    /** 所属行业 */
    getBelongAllList() {
      belongAllList().then(response => {
        this.belongAllList = response.data
      })
    },
    /** 联网单位 */
    getUpdateUnit() {
      allList().then(response => {
        this.updateUnitList = response.data
      })
    },
    /** 行政区域 */
    getRegionAllList() {
      regionAllList().then(response => {
        this.regionAllList = response.data
      })
    },
    /** 城市 */
    getCityList(val) {
      childrenCityList(val).then(response => {
        this.cityAllList = response.data
      })
    },
    /** 县区 */
    getDistrictList(val) {
      childrenDistrictList(val).then(response => {
        this.childrenAllList = response.data
      })
    },
    /** 联网单位所在区域 */
    getRegionList(val) {
      getSupervisorUnit(val).then(response => {
        this.getSupervisorlnitList = response.data
      })
      this.form.regionId = val
    },
    /** 联网单位 */
    getCustomMaintenanceUnit() {
      unitAllList().then(response => {
        this.customMaintenanceUnitList = response.data
      })
    },
    /** 国民经济 */
    getEconomicTypeList() {
      economicAllList().then(response => {
        this.economicTypeList = response.data
      })
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleDownload(file) {
      // 创建一个临时的a标签用于下载
      const link = document.createElement('a');
      link.href = file.url;
      link.download = file.name || 'downloaded-image'; // 如果没有文件名，使用默认名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.businessLicense = response.url;
      // this.msgSuccess(response.msg);
    },
    // 文件上传错误处理
    handleFileError(err, file, fileList) {
      this.upload.isUploading = false;
      this.msgError("上传失败:" + err.message);
    },
    // 上传前校验
    beforeFileUpload(file) {
      // 检查文件类型
      let isRightType = false;
      for (let i = 0; i < this.upload.fileTypes.length; i++) {
        let ext = file.name.substring(file.name.lastIndexOf("."));
        if (ext === this.upload.fileTypes[i]) {
          isRightType = true;
          break;
        }
      }
      if (!isRightType) {
        this.msgError(
          `请上传${this.upload.fileTypes.join("/")}格式文件!`
        );
        return false;
      }
      // 检查文件大小
      const isLtSize = file.size / 1024 / 1024 < this.upload.fileSize;
      if (!isLtSize) {
        this.msgError(`上传文件大小不能超过 ${this.upload.fileSize}MB!`);
        return false;
      }
      return true;
    },
    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.msgError(`每次只能上传一个文件!`);
    },
    getDictAllList(dictArray, labelKey, targetValue) {
      if (!Array.isArray(dictArray)) return '';
      const foundItem = dictArray.find(item => item.superviseOrgId === targetValue);
      console.log(dictArray, labelKey, targetValue, 11111111)
      return foundItem ? (foundItem[labelKey] || '') : '';
    }

  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
